package com.sanda.androidcourse.chapter11;

import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.sanda.androidcourse.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class JsonParseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_json_parse);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 从 assets 读取 JSON 数据
        String jsonString = loadJSONFromAsset();

        if (jsonString != null) {
            try {
                // 解析 JSON 字符串
                JSONObject jsonObject = new JSONObject(jsonString);

                // 获取 status 字段
                String status = jsonObject.getString("status");
                Log.d("JSON Parsing", "Status: " + status);

                // 获取 data 数组
                JSONArray dataArray = jsonObject.getJSONArray("data");

                // 遍历 data 数组
                for (int i = 0; i < dataArray.length(); i++) {
                    JSONObject userObject = dataArray.getJSONObject(i);

                    // 获取用户信息
                    int id = userObject.getInt("id");
                    String name = userObject.getString("name");
                    int age = userObject.getInt("age");

                    // 打印用户信息
                    Log.d("JSON Parsing", "User ID: " + id);
                    Log.d("JSON Parsing", "Name: " + name);
                    Log.d("JSON Parsing", "Age: " + age);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 从 assets 文件夹读取 JSON 文件
    private String loadJSONFromAsset() {
        String json = null;
        try {
            AssetManager assetManager = getAssets();
            InputStreamReader inputStreamReader = new InputStreamReader(assetManager.open("data.json"));
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            json = stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;

    }
}